<script setup lang="ts">
import { ElInput, ElTree } from 'element-plus'

import { pointApi } from '@/api'
import mitt from '@/bus'
import type { PointInfo } from '@/types'

const { vLoading, withLoading } = useDefineLoading()

const filterTextInput = ref<string>('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = shallowRef<PointInfo[]>([])
const defaultTreeExpandKeys = ref<number[]>([])
const current = ref<PointInfo>()

watch(
  () => filterTextInput.value,
  (val: string) => {
    treeRef.value?.filter?.(val)
  },
)

async function getTreeData() {
  try {
    const { data: res } = await withLoading(pointApi.loadRoleEnergyUnit)()
    if (!res || !res.list) {
      treeData.value = []
      defaultTreeExpandKeys.value = []
      return
    }
    treeData.value = res.list || []
    if (res.pointIdList === null) {
      defaultTreeExpandKeys.value = findAllIdFromTree(res.list, [])
    }
    else {
      defaultTreeExpandKeys.value = (res.pointIdList || []).map((v: string) => Number(v))
    }
    await nextTick()
    treeRef.value?.setCurrentKey(res.list[0]?.id)
    current.value = res.list[0]
  }
  catch (e) {}
}

function findAllIdFromTree(tree: any[], ids: number[]) {
  tree.forEach((item) => {
    ids.push(item.id)
    if (item.children && item.children.length > 0) {
      findAllIdFromTree(item.children, ids)
    }
  })
  return ids
}
function filterNode(value: string, data: any) {
  if (!value)
    return true
  return data.pointName?.includes(value)
}

function clickNode(data: any) {
  current.value = data
  mitt.emit('realtime-indicator-data:select-node', data)
}

let timer: ReturnType<typeof setInterval>
function interval() {
  mitt.emit(
    'realtime-indicator-data:select-node',
    current.value || {},
  )
}

onActivated(() => {
  if (timer) {
    clearInterval(timer)
  }
  timer = setInterval(interval, 10e3)
})

onBeforeUnmount(() => {
  clearInterval(timer)
})
onDeactivated(() => {
  clearInterval(timer)
})

onMounted(() => {
  if (timer) {
    clearInterval(timer)
  }
  timer = setInterval(interval, 10e3)
  getTreeData()
})
defineExpose({
  current,
  pause() {
    clearInterval(timer)
  },
  play() {
    if (timer) {
      clearInterval(timer)
    }
    timer = setInterval(interval, 10e3)
  },
})
</script>

<template>
  <div v-loading class="view-tree height-fill box-border">
    <h5
      class="flex-incompressible margin-0 align-center flex justify-between"
    >
      <span>用能单元（点位）</span>
    </h5>
    <ElInput
      v-model="filterTextInput"
      placeholder="关键字"
      clearable
      class="flex-incompressible free"
    />
    <ElScrollbar>
      <ElTree
        ref="treeRef"
        class="flex-fillRemaining"
        :data="treeData"
        :props="{
          label: 'pointName',
          children: 'children',
        }"
        node-key="id"
        highlight-current
        :default-expanded-keys="defaultTreeExpandKeys"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="clickNode"
      >
        <template #default="{ node }">
          <div
            class="flex-fillRemaining align-center custom-tree-node flex"
          >
            <span>{{ node.label }}</span>
          </div>
        </template>
      </ElTree>
    </ElScrollbar>
  </div>
</template>
